package com.tl.commonlibrary.ui.web;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Build;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.tl.commonlibrary.R;
import com.tl.commonlibrary.tool.Logger;

import cn.pedant.SafeWebViewBridge.InjectedChromeClient;

/**
 * Created by JongSung on 17/2/17.
 */

public class WebFragmentViewModel implements WebView.OnKeyListener {
    private WebFragment parent;
    public WebView webView;
    private WebFragmentModel model;
    private WebListener webListener;
    private ProgressBar progressBar;

    public WebFragmentViewModel(WebFragment parent) {
        this.parent = parent;
    }

    public void init() {
        initWebView();
    }

    public void setModel(WebFragmentModel model) {
        this.model = model;
    }

    private void initWebView() {
        progressBar = (ProgressBar) parent.getRoot().findViewById(R.id.progress);
        webView = (WebView) parent.getRoot().findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
        webView.getSettings().setSavePassword(false);
        webView.setBackgroundColor(Color.parseColor("#00000000"));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        int screenDensity = parent.getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
        switch (screenDensity) {
            case DisplayMetrics.DENSITY_LOW:
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
            default:
                break;
        }
        webView.getSettings().setDefaultZoom(zoomDensity);
        webView.getSettings().setLoadWithOverviewMode(true);

        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        webView.removeJavascriptInterface("accessibility");
        webView.removeJavascriptInterface("accessibilityTraversal");
        webView.setWebChromeClient(new InjectedChromeClient(model.getJavascriptName(), NativeJsScope.class) {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (webListener != null) {
                    webListener.onReceivedTitle(view, title);
                }
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (model.isShowProgress()) {//&& !parent.isLoading())
                    if (newProgress < 100) {
                        progressBar.setVisibility(View.VISIBLE);
                    } else {
                        progressBar.setVisibility(View.GONE);
                    }
                    progressBar.setProgress(newProgress);
                }
            }

        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (!model.isError()) {
                    webView.setVisibility(View.VISIBLE);
                } else {
                    webView.setVisibility(View.GONE);
                }
                model.resetErrorStatus();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!model.isError()) {
//                    parent.hideLoading();
                    progressBar.setVisibility(View.GONE);
                    webView.setVisibility(View.VISIBLE);
                    if (webListener != null) {
                        webListener.onPageFinished(view, url);
                    }
                }
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler,
                                           SslError error) {
                if (checkCerValidate(error.getCertificate())) {
                    handler.proceed();
                } else {
//                    Toast.makeText("ssl error").show();
                    handler.cancel();
                }
            }

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                error();
            }

            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                error();
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                //当前接口挂掉的话
                if (TextUtils.isEmpty(model.getUrl()) || model.getUrl().equals(request.getUrl().toString())) {
                    error();
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);
            }
        });
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                Logger.i("WebViewDownload", "url=" + url);
//                Logger.i("WebViewDownload", "userAgent=" + userAgent);
//                Logger.i("WebViewDownload", "contentDisposition=" + contentDisposition);
//                Logger.i("WebViewDownload", "mimetype=" + mimetype);
//                Logger.i("WebViewDownload", "contentLength=" + contentLength);
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                if (parent.getActivity() != null) {
                    parent.getActivity().startActivity(intent);
                } else {
                    parent.startActivity(intent);
                }
            }
        });
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setUserAgentString("Android");
        setUserAgent();
    }

    /**
     * 如何设置Url ？ {@link WebFragmentModel#setUrl(String)}
     */
    public void loadUrl() {
        String originalUrl = model.getOriginalUrl();
        if (TextUtils.isEmpty(originalUrl)) {
            return;
        }
        if (model.isShowProgress()) {
            parent.showLoading();
        }
        progressBar.setVisibility(View.GONE);
        model.setUrlByOrigin();
        webView.loadUrl(model.getUrl(), model.noCacheHeaders);
    }
    public void loadHtml(String data) {
        if (model.isShowProgress()) {
            parent.showLoading();
        }
        progressBar.setVisibility(View.GONE);
        webView.loadData(data, "text/html; charset=UTF-8", null);
    }
    public WebView getWebView() {
        return webView;
    }

    public View getRoot() {
        if (parent != null) {
            return parent.getRoot();
        }
        return null;
    }

    private final void setUserAgent() {
        String userAgent = webView.getSettings().getUserAgentString();
        //服务器端需要添加字段识别访问是不是来自手机端
        webView.getSettings().setUserAgentString(userAgent + ";android");
    }

    /**
     * 跳过证书验证
     *
     * @param certificate
     */
    private boolean checkCerValidate(SslCertificate certificate) {
//        try {
////            Bundle bundle = SslCertificate.saveState(certificate);
////            byte[] serverCerByte = bundle.getByteArray("x509-certificate");
//            byte[] serverCerByte = new byte[]{34, 13, 27, 33, 49};
//            byte[] localCerByte = new EquityCertificateVerification(Application..getAppContext()).getCertificate().getEncoded();
//            return !Arrays.equals(serverCerByte, localCerByte);
//        } catch (CertificateEncodingException e) {
//            e.printStackTrace();
//        }
        return true;
    }

    private void error() {
        model.setError(true);
        webView.setVisibility(View.GONE);
//        parent.showEmptyTips(parent.getString(R.string.load_failed));
//        parent.clickReload(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                loadUrl();
//            }
//        });
    }

    public void setWebListener(WebListener webListener) {
        this.webListener = webListener;
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (parent.canGoBack()) {
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    parent.goBack();
                }
                return true;
            }
        }
        return false;
    }
}
